package com.android.RssReader.Screen;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.RssReader.R;
import com.android.RssReader.RssReaderApplication;
import com.android.RssReader.Adapter.CustomSimpleAdapter;
import com.android.RssReader.Adapter.NewsBaseAdapter;
import com.android.RssReader.Model.NewsInfoBean;
import com.android.RssReader.Provider.NewsDatabaseHelper;
import com.android.RssReader.Service.ScreenService;
import com.android.RssReader.Service.ServiceManager;
import com.android.RssReader.Utils.DensityUtil;
import com.android.RssReader.Utils.Helper;
import com.android.RssReader.Utils.SecBase64;
import com.android.RssReader.Utils.XmlParserUtil;

public class ScreenHome extends Screen {
	private ListView mHomeListView;
	private LinearLayout mListFooter;
	private Button mListHeader;
	private LinearLayout mLoading;
	private TextView mTvMsg;
    private final int COLUMWIDTHPX = 55;
    private final int HorizontalSpacing = 10;
    private int mHorizontalSpacingDip;
    private int mColumnWidthDip;
    private final int  FLINGVELOCITYPX = 800;
    private int mFlingVelocutyDip;
    List<NewsInfoBean> list;
    private Handler mHandler;
    private ProgressDialog progressDialog;  
    private final int  GET_NEWS_OK = 1000;
    private final int  GET_NEWS_ERROR = 1001;
    private final int  GET_NEWS_MORE_OK = 1002;
    private final int  GET_NEWS_MORE_ERROR = 1003;
    private final int REFRESH_IN_FRONT = 2000;
    private final int REFRESH_IN_BACKGROUND = 2001;
    private Button refreshBtn, addBtn;
    private NewsBaseAdapter baseAdapter;
    private List<HashMap<String,String>> categories  = new ArrayList<HashMap<String,String>> ();;
    private GridView category;
    private CustomSimpleAdapter categoryAdapter;
    private static String RSS_URL = RssReaderApplication.NEWS_CATEGORY_DEFAULT1_URL;
    private static String CATEGORY = RssReaderApplication.NEWS_CATEGORY_DEFAULT1_NAME;
    private static int CategoryIndex = 0;
    private final ScreenService screenService;
    
	public static final int FAVORITES = Menu.FIRST;  
	public static final int SETTINGS = Menu.FIRST+1;  
    public static final int QUIT = Menu.FIRST+2;  
	    
	public ScreenHome() {
		super(SCREEN_TYPE.SCREEN_HOME_T, ScreenHome.class.getCanonicalName());
		screenService = ServiceManager.getScreenservice();
	}
   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		RssReaderApplication.LogD(ScreenHome.class, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_home);
		ServiceManager.start();
		list = new ArrayList<NewsInfoBean>();
		baseAdapter = new  NewsBaseAdapter(this, list);
		mColumnWidthDip = DensityUtil.px2dip(this, COLUMWIDTHPX);
		mFlingVelocutyDip = DensityUtil.px2dip(this, FLINGVELOCITYPX);
		mHorizontalSpacingDip = DensityUtil.px2dip(this, HorizontalSpacing);
		RssReaderApplication.LogD(ScreenHome.class, "mColumnWidthDip:" + mColumnWidthDip);
		mColumnWidthDip = DensityUtil.dip2px(this, COLUMWIDTHPX);
		RssReaderApplication.LogD(ScreenHome.class, "mColumnWidthDip:" + mColumnWidthDip);
		readCategoryCursor(true);
		categoryAdapter = new CustomSimpleAdapter(this, categories, R.layout.screen_home_categorybar_item, new String[] {"category_title"}, new int[] {R.id.title_tv});
		categoryAdapter.setPosition(0);
		category = new GridView(this);
		category.setColumnWidth(mColumnWidthDip);
		category.setHorizontalSpacing(mHorizontalSpacingDip);  
		category.setNumColumns(GridView.AUTO_FIT);
		category.setPadding(mHorizontalSpacingDip, 0, mHorizontalSpacingDip, 0);
		category.setGravity(Gravity.CENTER);
		category.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		category.setSelector(new ColorDrawable(Color.TRANSPARENT));
		int width = (mColumnWidthDip + mHorizontalSpacingDip)*categories.size() + 3*mHorizontalSpacingDip;
		DisplayMetrics dm=new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		LayoutParams params = category.getLayoutParams();
		RssReaderApplication.LogD(ScreenHome.class, "width:" + width);
		RssReaderApplication.LogD(ScreenHome.class, "screenWidth:" + dm.widthPixels);
		if (width < screenWidth) {
			 params = new LayoutParams(screenWidth, LayoutParams.WRAP_CONTENT);
		} else {
			 params = new LayoutParams(width, LayoutParams.WRAP_CONTENT); 
		}
		category.setLayoutParams(params);
		category.setAdapter(categoryAdapter);
		LinearLayout categoryLayout = (LinearLayout) findViewById(R.id.category_layout);
		categoryLayout.addView(category);
		
		category.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long arg3) {
				CategoryIndex = position;
				TextView categoryTitle;
				for(int i =0; i< parent.getCount(); i++){
					categoryTitle = (TextView) parent.getChildAt(i);
					categoryTitle.setTextColor(0XFFADB2AD);
					categoryTitle.setBackgroundDrawable(null);
				}
				categoryTitle = (TextView) view;
				categoryTitle.setTextColor(0XFFFFFFFF);
				categoryTitle.setBackgroundResource(R.drawable.image_categorybar_item_selected_background);
				RSS_URL = categories.get(position).get("category_url");
				CATEGORY = categories.get(position).get("category_title");
				Toast.makeText(ScreenHome.this, RSS_URL, Toast.LENGTH_SHORT).show();
				mHomeListView.setAdapter(null);
				Cursor c = ServiceManager.getNewsservice().getMediaDB().queryCountLocalNews(CATEGORY);
				if(c.getCount() == 0){
					c.close();
					list.clear();
					baseAdapter.setList(list);
					mHomeListView.setAdapter(baseAdapter);
					refresh(RSS_URL, CATEGORY, REFRESH_IN_FRONT);
				} else {
					changeCursor2List(c);
					baseAdapter.setList(list);
					mHomeListView.setAdapter(baseAdapter);
					refresh(RSS_URL, CATEGORY, REFRESH_IN_BACKGROUND);
				}
			}

			});
		
		category.setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				Toast.makeText(ScreenHome.this, "position:"+position, Toast.LENGTH_SHORT).show();
			    AlertDialog.Builder builder = new AlertDialog.Builder(ScreenHome.this); 
			    builder.setMessage(getString(R.string.dialog_delete_rss)) 
			           .setCancelable(false) 
			           .setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() { 
			               @Override
						public void onClick(DialogInterface dialog, int id) { 
			            	   if(position != 0 && position != 1){
			   					if(CategoryIndex == position){
			   						CategoryIndex = 0;
			   						RSS_URL = RssReaderApplication.NEWS_CATEGORY_DEFAULT1_URL;
			   						CATEGORY = RssReaderApplication.NEWS_CATEGORY_DEFAULT1_NAME;	
			   					}
			   					deleteCategory(categories.get(position).get("category_title"), categories.get(position).get("category_url"));
			   				}
			               } 
			           }) 
			           .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() { 
			               @Override
						public void onClick(DialogInterface dialog, int id) { 
			                    dialog.cancel(); 
			               } 
			           }); 
			    AlertDialog alert = builder.create(); 
			    alert.show();
				return false;
			}});
		
		final HorizontalScrollView categoryScrollView = (HorizontalScrollView)findViewById(R.id.category_scroll_view);
		
		Button categoryArrowRight = (Button)findViewById(R.id.right_btn);
		categoryArrowRight.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				categoryScrollView.fling(mFlingVelocutyDip);
			}
		});
		mListFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.list_footer, null);
		mTvMsg = (TextView) mListFooter.findViewById(R.id.tv_msg);
		mTvMsg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mLoading.setVisibility(View.VISIBLE);
				mTvMsg.setVisibility(View.GONE);
				refreshMore(RSS_URL, CATEGORY, REFRESH_IN_FRONT);
			}
		});
		mLoading = (LinearLayout) mListFooter.findViewById(R.id.loading);
		mListHeader = new Button(this);
		mListHeader.setText("搜新闻");
		mListHeader.setBackgroundResource(R.drawable.image_search_search_placeholder);
		mListHeader.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				screenService.show(ScreenSearch.class);
			}});
		mHomeListView = (ListView) findViewById(R.id.news_list);
		mHomeListView.addFooterView(mListFooter);
		mHomeListView.addHeaderView(mListHeader);
		mHomeListView.setOnItemClickListener(mItemClickListener);
		mHomeListView.setAdapter(baseAdapter);
		if(Helper.isOnline()){
			refresh(RSS_URL, CATEGORY, REFRESH_IN_FRONT);
		} else {
			Cursor c = ServiceManager.getNewsservice().getMediaDB().queryCountLocalNews(CATEGORY);
			if(c != null && c.getCount() != 0) {
				changeCursor2List(c);
				baseAdapter.setList(list);
			} else {
				c.close();
			}
		}
		
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case GET_NEWS_OK:
					RssReaderApplication.LogD(ScreenHome.class, "GET_NEWS_OK:" + list.size());
					baseAdapter.setList(list);
					break;
				case GET_NEWS_ERROR:
					Cursor c = ServiceManager.getNewsservice().getMediaDB().queryCountLocalNews(CATEGORY);
					if(c != null && c.getCount() != 0) {
						changeCursor2List(c);
						baseAdapter.setList(list);
					} else {
						c.close();
					}
					RssReaderApplication.LogD(ScreenHome.class, "GET_NEWS_ERROR:" + list.size());
					break;
				case GET_NEWS_MORE_OK:
					RssReaderApplication.LogD(ScreenHome.class, "GET_NEWS_MORE_OK:" + list.size());
					baseAdapter.setList(list);
					mLoading.setVisibility(View.GONE);
					mTvMsg.setVisibility(View.VISIBLE);
					break;
				case GET_NEWS_MORE_ERROR:
					RssReaderApplication.LogD(ScreenHome.class, "GET_NEWS_MORE_ERROR:" + list.size());
					mLoading.setVisibility(View.GONE);
					mTvMsg.setVisibility(View.VISIBLE);
					break;
				}
				if(progressDialog != null)
					progressDialog.dismiss(); 
			}
		};
		
		refreshBtn = (Button) findViewById(R.id.refresh_btn);
		refreshBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				refresh(RSS_URL, CATEGORY, REFRESH_IN_FRONT);
			}});
		
		addBtn = (Button) findViewById(R.id.add_btn);
		addBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				builderDialog1(ScreenHome.this).show();
				//screenService.show(ScreenCategory.class);
			}});
		
	}

	@Override
	protected void onDestroy() {
		RssReaderApplication.LogD(ScreenHome.class, "onDestroy");
		super.onDestroy();
	}
	
	
	public void changeCursor2List(Cursor c){
		list.clear();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			NewsInfoBean bean = new NewsInfoBean();
			bean.setTitle(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_TITLE)));
			bean.setDescription(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_DESCRIPTION)));
			bean.setAuthor(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_AUTHOR)));
			bean.setLink(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_LINK)));
			bean.setPubDate(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_DATE)));
			bean.setSource(c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_SOURCE)));
			list.add(bean);
		}
		c.close();
	}
	
	public void refresh(final String url, final String category, int type){
		if(type == REFRESH_IN_FRONT)
		progressDialog = ProgressDialog.show(ScreenHome.this, "Loading...", "Please wait...", true, false);
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					list = XmlParserUtil.PullParseXML(url, null);
					if(list != null && list.size() != 0) {
							mHandler.sendEmptyMessage(GET_NEWS_OK);
							for(int i =0; i < list.size(); i++) {
								if(!ServiceManager.getNewsservice().getMediaDB().isInLocalNews(list.get(i).getTitle())){
									ContentValues contentValues = new ContentValues();
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_ID, SecBase64.encode(list.get(i).getTitle().getBytes()));
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_TITLE, SecBase64.encode(list.get(i).getTitle().getBytes()));
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_DESCRIPTION, list.get(i).getDescription());
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_LINK, list.get(i).getLink());
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_SOURCE, list.get(i).getSource());
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_DATE, list.get(i).getPubDate());
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_AUTHOR, list.get(i).getAuthor());
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_READED, NewsDatabaseHelper.NEWS_IS_UNREAD);
									contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_CATEGORY, category);
									ServiceManager.getNewsservice().getMediaDB().insertCountLocalNews(contentValues);
									//RssReaderApplication.getInstance().listNewsCache.add(list.get(i));
								} else {
									RssReaderApplication.LogD(ScreenHome.class, "插入重复数据:" + list.get(i).getTitle());
								}
							}
					} else {
						mHandler.sendEmptyMessage(GET_NEWS_ERROR);
					}
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(GET_NEWS_ERROR);
				}				
			}}).start();
	}
	
	public void refreshMore(final String url, final String tag, int type){
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					list = XmlParserUtil.PullParseXML(url, list);
					if(list != null && list.size() != 0) {
							mHandler.sendEmptyMessage(GET_NEWS_MORE_OK);
					} else {
						mHandler.sendEmptyMessage(GET_NEWS_MORE_ERROR);
					}
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(GET_NEWS_MORE_ERROR);
				}				
			}}).start();
	}

	
	private OnItemClickListener mItemClickListener = new OnItemClickListener(){

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int position,
				long _id) {
			ScreenArgs args = (ScreenArgs) view.getTag();
			args.putExtra("category", CATEGORY);
			args.putExtra("item_id", _id);
			screenService.show(ScreenNewsContent.class, null , args, true);
		}
	};
	
	private Dialog builderDialog1(Context context) {
		LayoutInflater inflater = LayoutInflater.from(context);
		final View view = inflater.inflate(R.layout.screen_home_add_rss_dialog, null);

		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setIcon(R.drawable.image_titlebar_button_subscribe);
		dialog.setTitle(R.string.dialog_input_rss_name);
		dialog.setView(view);
		
		dialog.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				EditText nameText = (EditText)view.findViewById(R.id.rss_name_edit);
				EditText addressText = (EditText)view.findViewById(R.id.rss_address_edit);
				String rss_name = nameText.getText().toString();
				String rss_url = addressText.getText().toString();
				if(rss_name.equals("")) {
					Toast.makeText(ScreenHome.this, getString(R.string.dialog_input_rss_name_is_null), Toast.LENGTH_SHORT).show();
				}
				else if(rss_url.equals("")) {
					Toast.makeText(ScreenHome.this, getString(R.string.dialog_input_rss_url_is_null), Toast.LENGTH_SHORT).show();
				}
//				else if(!URLUtil.isNetworkUrl(rss_url)) {
//					Toast.makeText(ScreenHome.this, "RSS地址格式不正确!", Toast.LENGTH_SHORT).show();
//				}
				else {
					ContentValues contentValues = new ContentValues();
					contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_CAGETORY_NAME, rss_name);
					contentValues.put(NewsDatabaseHelper.COLUMN_NEWS_CAGETORY_URL, rss_url);
					ServiceManager.getNewsservice().getMediaDB().insertCountLocalCategorys(contentValues);
					readCategoryCursor(false);
				}
			}
		});
		
		dialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		return dialog.create();
	}
	
	
	private void readCategoryCursor(boolean isFist){
		Cursor c = ServiceManager.getNewsservice().getMediaDB().queryLocalCategorys();
		categories.clear();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
		    HashMap<String, String> hashMap = new HashMap<String,String>();
			hashMap.put("category_title", c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_CAGETORY_NAME)));
			hashMap.put("category_url", c.getString(c.getColumnIndexOrThrow(NewsDatabaseHelper.COLUMN_NEWS_CAGETORY_URL)));
			categories.add(hashMap);
		}
		if(!isFist) {
			//categoryAdapter = new CustomSimpleAdapter(this, categories, R.layout.screen_home_categorybar_item, new String[] {"category_title"}, new int[] {R.id.title_tv});
			categoryAdapter.setPosition(CategoryIndex);
			categoryAdapter.notifyDataSetChanged();
			changeGridViewParams();
			category.setAdapter(categoryAdapter);
		}
		c.close();
	}
	
	
	private void deleteCategory(String category_title, String category_url){
		ServiceManager.getNewsservice().getMediaDB().deleteCountLocalCategorys(category_title, category_url);
		readCategoryCursor(false);
	}
	
	private void changeGridViewParams(){
		int width = (mColumnWidthDip + mHorizontalSpacingDip)*categories.size() + 3*mHorizontalSpacingDip;
		DisplayMetrics dm=new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		LayoutParams params = category.getLayoutParams();
		if (width < screenWidth) {
			params.height = LayoutParams.WRAP_CONTENT;
	        params.width = screenWidth;        
		} else {
			params.height = LayoutParams.WRAP_CONTENT;
	        params.width = width;        
		}
		RssReaderApplication.LogD(ScreenHome.class, "params.width:" + params.width);
		category.setLayoutParams(params);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		RssReaderApplication.LogD(ScreenHome.class, "onNewIntent");
		super.onNewIntent(intent);
	}

	@Override
	protected void onPause() {
		RssReaderApplication.LogD(ScreenHome.class, "onPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		RssReaderApplication.LogD(ScreenHome.class, "onResume");
		super.onResume();
	}
	

	@Override
	protected void onStart() {
		RssReaderApplication.LogD(ScreenHome.class, "onStart");
		super.onStart();
	}

	@Override
	protected void onStop() {
		RssReaderApplication.LogD(ScreenHome.class, "onStop");
		super.onStop();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, FAVORITES, 0, "我的收藏");
		menu.add(0, SETTINGS, 1, "软件设置");
		menu.add(0, QUIT, 2, "退出");
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu){
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case FAVORITES:
			screenService.show(ScreenFavorites.class);
			break;
		case SETTINGS:
			screenService.show(ScreenSettings.class);
			break;
		case QUIT:
			ServiceManager.exit();
			break;
		}
		return true;
	}
	
	@Override
	public boolean haveMenu(){
		return true;
	}

	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0){
	    	    openOptionsMenu();
	    	    return true;
			}
		return super.onKeyDown(keyCode, event);
	}
	
}